

import { useEffect, useRef, useState } from "react";
import * as echarts from "echarts";
import { Space, DatePicker } from 'antd';
import moment from 'dayjs';
import Rose_DATA from "./lib/Rose_src.js";

//这里进行了年份选取限制，具体根据数据库来.
const disabledDate = (current) => {
	//数据库内只有2019
	return current < moment("2019") || current > moment("2022")
};

function DatePick({ DefaultText, onChange }) {
	return (
		<div>
			<DatePicker picker="year" onChange={onChange} placeholder={DefaultText} disabledDate={disabledDate} allowClear={true} />
		</div>
	)
}

function RoseChart(props) {
	const title = props.title;
	const style = props.style;
	const kind = props.kind - 1;
	const [year1, setYear1] = useState('')
	const [year2, setYear2] = useState('')
	const [year3, setYear3] = useState('')
	//3个不同的Change对应三次年份选择
	const onChange1 = (value, dateString) => {
		setYear1(dateString);
	}
	const onChange2 = (value, dateString) => {
		setYear2(dateString);
	}
	const onChange3 = (value, dateString) => {
		setYear3(dateString);
	}

	const chartRef = useRef(null);

	const chartInit = () => {
		//labelData为企业总数前五省份信息，存储在Rose_DATA[kind][0]这一数组中
		var labelData = Rose_DATA[kind][0].map(function (item) {
			return { name: item[0], value: 7 };
		})
		//console.log("label:", labelData)

		//data存储选取的三年数据，属性包括id(省份+年份),name（省份）,value（企业数）
		var data = [];
		for (var i = 0; i < labelData.length; i++) {
			if (year1 !== '') data.push({ id: labelData[i].name + year1, name: labelData[i].name, value: 0 });
			if (year2 !== '') data.push({ id: labelData[i].name + year2, name: labelData[i].name, value: 0 })
			if (year3 !== '') data.push({ id: labelData[i].name + year3, name: labelData[i].name, value: 0 })
		}
		//console.log("data1", data)

		//convertData从Rose_DATA中找到 省份和年份均匹配的数据 ，赋给data的value属性
		const convertData = function (data) {
			for (var i = 1; i < Rose_DATA[kind].length; i++) {
				var item = Rose_DATA[kind][i];
				var index;
				index = data.findIndex(function (e) {
					return e.id === item[0] + item[1]
				})
				if (index !== -1) {
					data[index].value = item[2];
				}
			}
			return data;
		};
		var myChart;
		//这一步操作是继承上一次使用过的dom，提高运行效率
		const renderedInstance = echarts.getInstanceByDom(chartRef.current);
		if (renderedInstance) {
			myChart = renderedInstance;
		} else {
			myChart = echarts.init(chartRef.current);
		}
		myChart.setOption({
			backgroundColor: '#fff',
			title: {
				text: title,
				left: '1%',
				top: '1%',
				textStyle: {
					color: "#0C2A40",
					fontSize: "12"
				}
			},
			tooltip: {
				trigger: 'item',

			},
			toolbox: {
				show: true,
				feature: {
					dataView: { show: true, readOnly: false, title: "查看数据" },
					restore: { show: true, title: "恢复到初始状态" },
					saveAsImage: { show: true, title: "另存为图片" },
				}
			},

			//带有阴影强化，可选择移除
			series: [{
				type: 'pie',
				data: convertData(data),
				radius: ['20%', '70%'],
				center: ['50%', '50%'],
				roseType: 'area',
				itemStyle: {
					//原来的图太尖锐了，这里加了圆角
					borderRadius: 8,
				},
				avoidLabelOverlap: true,
				emphasis: {
					label: {
						show: true,
						formatter:function(params){
							return params.data.id;
						},
						fontSize: 20,
						fontWeight: 'bold',
					}
				},
				label: {
					show:true,
					formatter:function(params){
						//默认情况下显示 ”省份首字+年份尾两字“
						return params.data.name[0]+params.data.id.slice(params.data.name.length+2);
					},
					position: 'inside'
				},
				animationType: 'scale',
				animationEasing: 'elasticOut',
				animationDelay: function (idx) {
					return Math.random() * 200;
				}
			},
			//圆环内容 
			{
				type: 'pie',
				data: labelData,
				radius: ['80%', '97%'],
				zlevel: -2,
				itemStyle: {
					normal: {
						color: '#4682B4',
						borderColor: '#0F5FA0'
					}
				},
				label: {
					color: '#FFFFFF',
					borderColor: '#000000',
					position: 'inside'

				}
			},

			]
		})
		//这一部分是采用页面大小适配
		window.addEventListener('resize', function () {
			myChart.resize();
		});
	}

	//useEffect部分的警告请忽略
	useEffect(() => {
		chartInit();
	}, [year1, year2, year3, kind]);

	return (
		<div>
			{/* 玫瑰图年份选择按钮 */}
			<Space direction="horizontal" size={12} style={{ paddingLeft: 9, paddingTop: 9 }}>
				<DatePick onChange={onChange1} DefaultText={"年份1"} />
				<DatePick onChange={onChange2} DefaultText={"年份2"} />
				<DatePick onChange={onChange3} DefaultText={"年份3"} />
			</Space>
			{/*准备挂载节点*/}
			<div ref={chartRef} style={style}></div>
		</div>

	);
}

export default RoseChart;